package com.yimi.yinhepda.views.exceptionsUpload_module;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.liji.imagezoom.util.ImageZoom;
import com.pda.ym.utils.SysInfo;
import com.yimi.yinhepda.BuildConfig;
import com.yimi.yinhepda.R;
import com.yimi.yinhepda.adapter.SpinnerAdapter;
import com.pda.ym.base.BaseTitleActivity;
import com.pda.ym.callbacks.UICallBack;
import com.yimi.yinhepda.db.dao.QueryQcTypeTableDao;
import com.yimi.yinhepda.db.dao.UCDeptTableDao;
import com.yimi.yinhepda.db.table.QueryQcTypeTable;
import com.yimi.yinhepda.db.table.UCDeptTable;
import com.yimi.yinhepda.entity.bean.UcProblemReportEntity;
import com.yimi.yinhepda.entity.bean.UcProblemTypeEntity;
import com.yimi.yinhepda.entity.request.Abnormal;
import com.yimi.yinhepda.entity.response.BooleanDataResponse;
import com.yimi.yinhepda.entity.response.IntDataResponse;
import com.pda.ym.entity.bean.ImageInfo;
import com.pda.ym.entity.bean.ImageInfoResponse;
import com.yimi.yinhepda.entity.response.QueryQcType;
import com.yimi.yinhepda.entity.response.QueryQcTypeTableResponse;
import com.yimi.yinhepda.entity.response.QueryUcOrderTypeResponse;
import com.yimi.yinhepda.entity.response.QueryWybillExtendVoByWaybillNoArrayResponse;
import com.yimi.yinhepda.entity.response.UcProblemReportResponse;
import com.yimi.yinhepda.entity.response.WaybillExtend;
import com.pda.ym.net.NetRequest;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.Constants;
import com.pda.ym.utils.DateHelper;
import com.pda.ym.utils.FastClick;
import com.yimi.yinhepda.utils.GalleryPickView;
import com.yimi.yinhepda.utils.IntentUtils;
import com.pda.uce.commom.util.LogUtil;
import com.pda.uce.commom.util.MyDialog;
import com.yimi.yinhepda.utils.PermissionUtils;
import com.pda.ym.utils.SharedPreferUtil;
import com.pda.ym.utils.SoundVibratorManager;
import com.yimi.yinhepda.utils.TipHelper;
import com.yimi.yinhepda.utils.UcWaybillValidate;
import com.yimi.yinhepda.views.createPackage_module.CreateDeptSelectActivity;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 问题件上报界面
 *
 * @author 000432
 */
public class ProblemBillUploadActivity extends BaseTitleActivity implements AdapterView.OnItemSelectedListener {
    /**
     * 运单号
     */
    private EditText etWaybill;
    /**
     * 异常件数
     */
    private RelativeLayout rlExptionNum;
    /**
     * 问题件类别、是否修复、车牌号、配载单号、是否转差错、派送日期
     */
    private LinearLayout llProblemCategory, llIsRepair, llCarNo, llStowageNo, llIsChaCuo, llDispatchTime;
    /**
     * 派送日期
     */
    private TextView tvDispatchTime;
    /**
     * 车牌号
     */
    private EditText carNo;
    /**
     * 配载单号
     */
    private EditText etCarCode;
    /**
     * 异常件数
     */
    private EditText exceptionNum;
    /**
     * 备注
     */
    private EditText et_remark;
    /**
     * 上报类型
     */
    private Spinner uploadTypeSpinner;
    /**
     * 上报类别
     */
    private Spinner uploadType2Spinner;
    /**
     * 差错类型
     */
    private Spinner chaCuoSpinner;
    /**
     * 接收企业
     */
    private Spinner provinceSpinner;

    private QueryQcTypeTableDao mQueryQcTypeTableDao = new QueryQcTypeTableDao();
    /**
     * 问题件
     */
    private List<QueryQcTypeTable> list;
    private List<QueryQcTypeTable> list2;
    private List<String> splist1 = new ArrayList<>();
    private List<String> splist2 = new ArrayList<>();
    private List<String> spListIsRepair = new ArrayList<>();
    private List<String> chaCuoList = new ArrayList<>();
    private SpinnerAdapter<String> adapterType, adapterType2, chaCuoAdapter;
    private SpinnerAdapter adapterIsRepair;
    /**
     * 需要回复
     */
    private TextView tvNeedReply;
    /**
     * 责任部门
     */
    private TextView tvZenRenDept;
    private String zeRenDept;
    private String zeRenDeptCode;
    private final int ZE_REN_DEPT_CODE = 100;
    private LinearLayout llZeRenDept;
    /**
     * 开单件数
     */
    private Integer waybillNum;
    /**
     * 运单是否存在
     */
    private boolean hasWaybill = false;
    /**
     * 运单号必填tag
     */
    private TextView tvWaybillTag;
    /**
     * 配载单号必填tag
     */
    private TextView tvStowageNoTag;
    /**
     * 是否修复
     */
    private Spinner spIsRepair;
    /**
     * 0 - PDA校验运单号必填即可。
     * 1 - PDA需校验配载单必填，运单号不可填。
     */
    private int mIsStowageNo;
    private boolean isRequesting = false;
    private GalleryPickView mGalleryPickView;
    /**
     * 修复前照片IDs
     */
    private String mImageBeforeIds;
    /**
     * 修复后照片IDs
     */
    private String mImageAfterIds;
    /**
     * 正常照片上传
     */
    private String mImageIds;
    /**
     * 快递问题件类型
     */
    private List<UcProblemTypeEntity> mUcProblemTypeEntityList;
    private boolean isRepairFirst = true;
    private boolean isChaCuoFirst = true;

    public ProblemBillUploadActivity() {
        super(true);
    }

    @Override
    public int setContentViewId() {
        return R.layout.activity_problem_bill_upload;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        getQC2Data();
    }

    @Override
    public String getPageName() {
        return "问题件上传";
    }

    /**
     * 请求获取问题件类型
     */
    private void getQC2Data() {
        showPgDlg("数据获取中...");
        new NetRequest().setMethod(NetRequest.Method.GET)
                .setResponsClazz(QueryQcTypeTableResponse.class)
                .setUrl(Constants.URL_QUERY_QC_TYPE)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        showToast(msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        QueryQcTypeTableResponse response = (QueryQcTypeTableResponse) obj;
                        if (response.getData() != null) {
                            List<QueryQcType> list = response.getData();
                            if (list != null && !list.isEmpty()) {
                                LogUtil.e("问题件总数=" + list.size());
                                QueryQcTypeTableDao qcTypeTableDao = new QueryQcTypeTableDao();
                                qcTypeTableDao.deleteAll();
                                qcTypeTableDao.createOrUpdate(list);
                                initData();
                            }
                        }
                    }
                });
    }

    private void initData() {
        //设置焦点
        etWaybill.setFocusable(true);
        etWaybill.setFocusableInTouchMode(true);
        etWaybill.requestFocus();

        //派送日期默认隐藏
        llDispatchTime.setVisibility(View.GONE);
        //是否转差错默认隐藏
        llIsChaCuo.setVisibility(View.GONE);

        //设置问题件的类型
        setProblemType();
        //操作类型，1-装车，2-卸车
        int operTypeCode = getIntent().getIntExtra(IntentUtils.OPER_TYPE_CODE, -1);
        if (operTypeCode == 2) {
            //获取卸车跳转过来的车牌号
            String carNoStr = getIntent().getStringExtra(IntentUtils.CAR_NO);
            if (carNoStr != null) {
                carNo.setText(carNoStr);
            }
            String stowageNo = getIntent().getStringExtra(IntentUtils.STOWAGENO);
            if (stowageNo != null) {
                etCarCode.setText(stowageNo);
            }
        }

        //是否修复
        spListIsRepair.add("是");
        spListIsRepair.add("否");
        adapterIsRepair = new SpinnerAdapter<>(this, R.layout.simple_spinner_item, spListIsRepair);
        spIsRepair.setAdapter(adapterIsRepair);
        spIsRepair.setSelection(1);

        //是否转差错
        setChaCuoType();

        //获取跳转过来的运单号
        String wayBillNo = getIntent().getStringExtra(IntentUtils.WAYBILLNO);
        if (wayBillNo != null) {
            if (UcWaybillValidate.validate(wayBillNo)) {
                //隐藏快运内容
                kuaiYunGone();
                //查询快递问题件类型
                queryUcProblemType(wayBillNo);
            } else {
                //显示快运内容
                kuaiYunVisible();
                //查询运单信息
                queryWayBill(wayBillNo);
            }
        }

        etWaybill.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                String strWayBill = etWaybill.getText().toString().trim();
                if (!"".equals(strWayBill)) {
                    if (UcWaybillValidate.validate(strWayBill)) {
                        //隐藏快运内容
                        kuaiYunGone();
                        if (!isRequesting) {
                            //查询快递问题件类型
                            queryUcProblemType(strWayBill);
                        }
                    } else {
                        //显示快运内容
                        kuaiYunVisible();
                        //设置问题件的类型
                        setProblemType();
                        if (strWayBill.length() == 12) {
                            if (!isRequesting) {
                                //查询运单信息
                                queryWayBill(strWayBill);
                            }
                        }
                    }
                }
            }
        });

        mGalleryPickView.getIvPicTake0().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //照片上传
                mGalleryPickView.setPicType(3);
                mGalleryPickView.takePhotoFunction(ProblemBillUploadActivity.this);
            }
        });

        mGalleryPickView.getmTakePhotoGridView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                //照片上传
                mGalleryPickView.setPicType(3);
                if (mGalleryPickView.isCanTakePhoto3() && position == mGalleryPickView.getPickPicTakePhoto().size()) {
                    //如果可以拍照且位置为相册的最后一个,进入相册
                    mGalleryPickView.takePhotoFunction(ProblemBillUploadActivity.this);
                } else {
                    ImageZoom.show(ProblemBillUploadActivity.this, position, mGalleryPickView.getPickPicTakePhoto());
                }
            }
        });

        mGalleryPickView.getmTakePhotoGridView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                deletePicDialog(3, position, mGalleryPickView.getPickPicTakePhoto());
                return true;
            }
        });

        mGalleryPickView.getIvPicTake().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //修复前照片
                mGalleryPickView.setPicType(1);
                mGalleryPickView.takePhotoFunction(ProblemBillUploadActivity.this);
            }
        });

        mGalleryPickView.getmGridView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                //修复前照片
                mGalleryPickView.setPicType(1);
                if (mGalleryPickView.isCanTakePhoto1() && position == mGalleryPickView.getPickPicBefor().size()) {
                    //如果可以拍照且位置为相册的最后一个,进入相册
                    mGalleryPickView.takePhotoFunction(ProblemBillUploadActivity.this);
                } else {
                    ImageZoom.show(ProblemBillUploadActivity.this, position, mGalleryPickView.getPickPicBefor());
                }
            }
        });

        mGalleryPickView.getmGridView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                deletePicDialog(1, position, mGalleryPickView.getPickPicBefor());
                return true;
            }
        });

        mGalleryPickView.getIvPicTake2().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //修复后照片
                mGalleryPickView.setPicType(2);
                mGalleryPickView.takePhotoFunction(ProblemBillUploadActivity.this);
            }
        });

        mGalleryPickView.getmGridView2().setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                //修复后照片
                mGalleryPickView.setPicType(2);
                if (mGalleryPickView.isCanTakePhoto2() && position == mGalleryPickView.getPickPicAfter().size()) {
                    //如果可以拍照且位置为相册的最后一个,进入相册
                    mGalleryPickView.takePhotoFunction(ProblemBillUploadActivity.this);
                } else {
                    ImageZoom.show(ProblemBillUploadActivity.this, position, mGalleryPickView.getPickPicAfter());
                }
            }
        });

        mGalleryPickView.getmGridView2().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                deletePicDialog(2, position, mGalleryPickView.getPickPicAfter());
                return true;
            }
        });
    }

    /**
     * 设置问题件类型
     */
    private void setProblemType() {
        splist1.clear();
        list = mQueryQcTypeTableDao.findLevel(1);
        if (list != null && list.size() > 0) {
            for (QueryQcTypeTable item : list) {
                splist1.add(item.getTypeName());
            }
        }
        // 建立Adapter并且绑定数据源
        adapterType = new SpinnerAdapter<>(this, R.layout.simple_spinner_item, splist1);
        uploadTypeSpinner.setAdapter(adapterType);
    }

    /**
     * 设置快递问题件类型
     */
    private void setUcProblemType(List<UcProblemTypeEntity> list) {
        splist1.clear();
        if (list != null && !list.isEmpty()) {
            mUcProblemTypeEntityList = list;
            for (UcProblemTypeEntity item : list) {
                splist1.add(item.getTypeName());
            }
        }
        // 建立Adapter并且绑定数据源
        adapterType = new SpinnerAdapter<>(this, R.layout.simple_spinner_item, splist1);
        uploadTypeSpinner.setAdapter(adapterType);
    }

    /**
     * 是否差错
     */
    private void setChaCuoType() {
        chaCuoList.add("是");
        chaCuoList.add("否");
        chaCuoAdapter = new SpinnerAdapter<>(this, R.layout.simple_spinner_item, chaCuoList);
        chaCuoSpinner.setAdapter(chaCuoAdapter);
        chaCuoSpinner.setSelection(1, true);
    }

    /**
     * 删除图片对话框
     *
     * @param picType  照片类型：1-修复前照片，2-修复后照片，3-正常照片
     * @param position
     * @param list
     */
    private void deletePicDialog(int picType, final int position, final List<String> list) {
        if (position + 1 > list.size()) {
            return;
        }
        //照片上传
        mGalleryPickView.setPicType(picType);
        //震动
        TipHelper.Vibrate(ProblemBillUploadActivity.this, 500);
        MyDialog deleteDialog = new MyDialog(ProblemBillUploadActivity.this);
        deleteDialog.setIcon(R.drawable.alert);
        deleteDialog.setMessage("确定删除该图片吗?");
        deleteDialog.setPositiveClickListener("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                list.remove(position);
                mGalleryPickView.resetPicture(list);
            }
        });
        deleteDialog.setNegativeClickListener(R.drawable.btn_cancel_selector, "取消", null);
        deleteDialog.show();
    }

    @Override
    protected void handleBarCode(String result) {
        if (result == null) {
            return;
        }

        if (UcWaybillValidate.validate(result)) {
            //隐藏快运内容
            kuaiYunGone();
            //查询快递问题件类型
            queryUcProblemType(result);
        } else {
            if (result.length() > 12) {
                result = result.substring(0, 12);
            } else if (result.length() != 12) {
                showToast("运单号不规范!");
                SoundVibratorManager.playSound(2);
                return;
            }
            //显示快运内容
            kuaiYunVisible();
            //设置问题件的类型
            setProblemType();
            //查询运单信息
            queryWayBill(result);
        }
    }


    /**
     * 查询快递问题件类型
     */
    private void queryUcProblemType(String result) {
        isRequesting = true;
        etWaybill.setText(result);
        showPgDlg("查询问题件类型...");
        new NetRequest().setMethod(NetRequest.Method.GET)
                .setUrl(Constants.URL_GET_ORDER_TYPE)
                .setParams(null)
                .setResponsClazz(QueryUcOrderTypeResponse.class)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        isRequesting = false;
                        dismissPgDlg();
                        showToast(msg);
                        SoundVibratorManager.playSound(2);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        isRequesting = false;
                        dismissPgDlg();
                        QueryUcOrderTypeResponse response = (QueryUcOrderTypeResponse) obj;
                        if (response.getData() != null && response.getData().isSuccess()) {
                            //设置快递问题件类型
                            setUcProblemType(response.getData().getResult());
                        }
                        SoundVibratorManager.playSound(1);
                    }
                });

    }

    private void queryWayBill(String str) {
        isRequesting = true;
        etWaybill.setText(str);
        setScannerEnabled(false);

        Map params = new HashMap();
        params.put("waybillNoArray", str);
        new NetRequest().setMethod(NetRequest.Method.GET)
                .setUrl(Constants.URL_GETWAYBILL)
                .setParams(params)
                .setResponsClazz(QueryWybillExtendVoByWaybillNoArrayResponse.class)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        isRequesting = false;
                        hasWaybill = false;
                        setScannerEnabled(true);
                        SoundVibratorManager.playSound(2);
                        if (msg != null) {
                            showToast("查询运单信息失败:" + msg);
                        } else {
                            showToast("查询运单信息失败!");
                        }
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        isRequesting = false;
                        setScannerEnabled(true);
                        QueryWybillExtendVoByWaybillNoArrayResponse response = (QueryWybillExtendVoByWaybillNoArrayResponse) obj;
                        if (response != null) {
                            if (response.getData() != null && response.getData().getWaybillExtendList() != null) {
                                hasWaybill = true;
                                WaybillExtend waybillExtend = response.getData().getWaybillExtendList().get(0);
                                waybillNum = waybillExtend.getQuantity();
                                SoundVibratorManager.playSound(1);
                            } else {
                                hasWaybill = false;
                                SoundVibratorManager.playSound(2);
                                if (response.getErrorMessages() != null && response.getErrorMessages().length > 0) {
                                    showToast(response.getErrorMessages()[0]);
                                } else {
                                    showToast("查询运单信息失败!");
                                }
                            }
                        }
                    }
                });
    }

    public void initView() {
        tvWaybillTag = findViewById(R.id.tv_waybillTag);
        tvStowageNoTag = findViewById(R.id.tv_stowageNoTag);
        findViewById(R.id.problembill_save).setOnClickListener(this);
        findViewById(R.id.problembill_back).setOnClickListener(this);
        uploadTypeSpinner = findViewById(R.id.spinner_uploadType);
        uploadTypeSpinner.setOnItemSelectedListener(this);
        uploadType2Spinner = findViewById(R.id.spinner_uploadType2);
        uploadType2Spinner.setOnItemSelectedListener(this);
        provinceSpinner = findViewById(R.id.spinner_province);
        provinceSpinner.setOnItemSelectedListener(this);
        etWaybill = findViewById(R.id.et_waybill);
        etCarCode = findViewById(R.id.et_carCode);
        carNo = findViewById(R.id.et_carNo);
        exceptionNum = findViewById(R.id.exception_num);
        et_remark = findViewById(R.id.et_remark);
        tvNeedReply = findViewById(R.id.tv_needReply);
        tvZenRenDept = findViewById(R.id.tv_zeRenDept);
        tvZenRenDept.setOnClickListener(this);
        //责任部门
        llZeRenDept = findViewById(R.id.ll_zeRenDept);
        spIsRepair = findViewById(R.id.spinner_isRepair);
        spIsRepair.setOnItemSelectedListener(this);
        //照片上传
        mGalleryPickView = findViewById(R.id.gv_pic_repair);
        //异常件数
        rlExptionNum = findViewById(R.id.rl_exception_num);
        //问题件类别
        llProblemCategory = findViewById(R.id.ll_problem_category);
        //是否修复
        llIsRepair = findViewById(R.id.ll_is_repair);
        //车牌号
        llCarNo = findViewById(R.id.ll_car_no);
        //配载单号
        llStowageNo = findViewById(R.id.ll_stowage_no);
        //是否转差错
        llIsChaCuo = findViewById(R.id.ll_isChaCuo);
        chaCuoSpinner = findViewById(R.id.spinner_isChaCuo);
        chaCuoSpinner.setOnItemSelectedListener(this);
        //派送日期
        llDispatchTime = findViewById(R.id.ll_dispatchTime);
        tvDispatchTime = findViewById(R.id.tv_dispatchTime);
        tvDispatchTime.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (FastClick.isFastClick()) {
            return;
        }
        switch (v.getId()) {
            case R.id.problembill_back:
                finish();
                break;
            case R.id.tv_dispatchTime:
                //派送日期
                TimePickerDialog timePickerDialog = new TimePickerDialog.Builder().setCallBack(new OnDateSetListener() {
                    @Override
                    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
                        String time = DateHelper.getDateToString(millseconds, DateHelper.dateFormat);
                        tvDispatchTime.setText(time);
                    }
                })
                        .setCancelStringId("取消")
                        .setSureStringId("确定")
                        .setTitleStringId("选择")
                        .setYearText("年")
                        .setMonthText("月")
                        .setDayText("日")
                        .setCyclic(false)
                        //设置能获取的最小值getMills（）是获取时间毫秒值
                        .setMinMillseconds(System.currentTimeMillis())
                        //设置能到达的最大值
                        .setMaxMillseconds(DateHelper.getDifferenceTime(7))
                        //设置当前时间
                        .setCurrentMillseconds(System.currentTimeMillis())
                        .setThemeColor(getResources().getColor(R.color.timepicker_dialog_bg))
                        .setType(Type.YEAR_MONTH_DAY)
                        .setWheelItemTextNormalColor(getResources().getColor(R.color.timepicker_dialog_bg))
                        .setWheelItemTextSelectorColor(getResources().getColor(R.color.timepicker_toolbar_bg))
                        .setWheelItemTextSize(12)
                        .build();
                timePickerDialog.show(getSupportFragmentManager(), "YEAR_MONTH_DAY");
                break;
            case R.id.tv_zeRenDept:
                //责任部门
                Intent intent1 = new Intent(this, CreateDeptSelectActivity.class);
                intent1.putExtra("inputType", 4);
                intent1.putExtra("currentDept", sharedPreferUtil.getDeptCode());
                startActivityForResult(intent1, ZE_REN_DEPT_CODE);
                break;
            case R.id.problembill_save:
                //问题件上传
                save();
                break;
            default:
                break;
        }
    }

    /**
     * 快运内容隐藏
     */
    private void kuaiYunGone() {
        llZeRenDept.setVisibility(View.GONE);
        mGalleryPickView.setVisibility(View.GONE);
        rlExptionNum.setVisibility(View.GONE);
        llProblemCategory.setVisibility(View.GONE);
        llIsRepair.setVisibility(View.GONE);
        llCarNo.setVisibility(View.GONE);
        llStowageNo.setVisibility(View.GONE);
        et_remark.setHint("备注(非必填)");
    }

    /**
     * 快运内容显示
     */
    private void kuaiYunVisible() {
        llZeRenDept.setVisibility(View.VISIBLE);
        mGalleryPickView.setVisibility(View.VISIBLE);
        rlExptionNum.setVisibility(View.VISIBLE);
        llProblemCategory.setVisibility(View.VISIBLE);
        llIsRepair.setVisibility(View.VISIBLE);
        llCarNo.setVisibility(View.VISIBLE);
        llStowageNo.setVisibility(View.VISIBLE);
        et_remark.setHint("问题详情300字以内(必填)");
    }

    private void save() {
        String waybill = etWaybill.getText().toString();
        if (UcWaybillValidate.validate(waybill)) {
            //提交快递问题件
            submitUcProblem();
        } else {
            if (mIsStowageNo == 0) {
                if ("".equals(waybill)) {
                    SoundVibratorManager.playSound(2);
                    showToast("请输入运单");
                    return;
                }
                if (waybill.length() != 12) {
                    SoundVibratorManager.playSound(2);
                    showToast("运单号不正确");
                    return;
                }
                if (!hasWaybill) {
                    SoundVibratorManager.playSound(2);
                    showToast("运单号不存在!");
                    return;
                }
            }
            if (uploadTypeSpinner.getSelectedItemPosition() < 0) {
                SoundVibratorManager.playSound(2);
                showToast("请选择问题类型");
                return;
            }

            if (uploadType2Spinner.getSelectedItemPosition() < 0) {
                SoundVibratorManager.playSound(2);
                showToast("请选择问题类别");
                return;
            }
            String expNum = exceptionNum.getText().toString().trim();
            if (!expNum.equals("") && Integer.parseInt(expNum) <= 0) {
                SoundVibratorManager.playSound(2);
                showToast("异常件数不能小于等于0！");
                return;
            }

            if (waybillNum != null && !expNum.equals("") && Integer.parseInt(expNum) > waybillNum) {
                SoundVibratorManager.playSound(2);
                showToast("异常件数不可大于开单件数！");
                return;
            }

            if (llDispatchTime.getVisibility() == View.VISIBLE && "".equals(tvDispatchTime.getText().toString())) {
                SoundVibratorManager.playSound(2);
                showToast("请选择派送时间！");
                return;
            }

            if (llZeRenDept.getVisibility() == View.VISIBLE && tvZenRenDept.getText().toString().equals("")) {
                SoundVibratorManager.playSound(2);
                showToast("请选择责任部门！");
                return;
            }

            if (mIsStowageNo == 1 && "".equals(etCarCode.getText().toString().trim())) {
                SoundVibratorManager.playSound(2);
                showToast("请输入配载单号！");
                return;
            }

            String strRemark = et_remark.getText().toString().trim();
            if (strRemark.equals("")) {
                SoundVibratorManager.playSound(2);
                showToast("请输入问题详情！");
                return;
            }
            if (strRemark.length() > 300) {
                SoundVibratorManager.playSound(2);
                showToast("不能超过300字！");
                return;
            }

            //是否修复
            if (spIsRepair.getVisibility() == View.VISIBLE) {
                if (spIsRepair.getSelectedItemPosition() == 0) {
                    //是否修复，选择是
                    if (mGalleryPickView.getPickPicBefor().size() < 2) {
                        showToast("至少上传两张修复前照片");
                        SoundVibratorManager.playSound(2);
                        return;
                    }
                    if (mGalleryPickView.getPickPicAfter().size() < 2) {
                        showToast("至少上传两张修复后照片");
                        SoundVibratorManager.playSound(2);
                        return;
                    }
                } else {
                    //是否修复，选择否
                    if (mGalleryPickView.getPickPicTakePhoto().size() < 1) {
                        showToast("至少一张拍照上传");
                        SoundVibratorManager.playSound(2);
                        return;
                    }
                }
            } else {
                if (checkProblemBillUpPic() && (mGalleryPickView.getPickPicTakePhoto() == null || mGalleryPickView.getPickPicTakePhoto().isEmpty())) {
                    //符合问题类别的问题件将必须提供照片
                    showToast("需提供照片！");
                    SoundVibratorManager.playSound(2);
                    return;
                }
            }
            //上传图片
            uploadImage(1);
        }
    }

    /**
     * 提交快递问题件
     */
    private void submitUcProblem() {

        if (uploadTypeSpinner.getSelectedItemPosition() < 0) {
            SoundVibratorManager.playSound(2);
            showToast("请选择问题类型！");
            return;
        }
        if (mUcProblemTypeEntityList == null || mUcProblemTypeEntityList.isEmpty()) {
            SoundVibratorManager.playSound(2);
            showToast("未查询到快递问题类型！");
            return;
        }

        UcProblemReportEntity reportEntity = new UcProblemReportEntity();
        UcProblemTypeEntity ucProblemTypeEntity = mUcProblemTypeEntityList.get(uploadTypeSpinner.getSelectedItemPosition());
        reportEntity.setProblemCauses(ucProblemTypeEntity.getTypeName());
        reportEntity.setScanCode(etWaybill.getText().toString().trim());
        reportEntity.setScanTime(DateHelper.getDateTimeFormate(new Date()));
        reportEntity.setScanEmpCode(sharedPreferUtil.getValue(Common.USER_CODE));
        reportEntity.setScanOrgCode(sharedPreferUtil.getDeptCode());
        reportEntity.setTaskType("PDA_SCAN_PROBLEM_PIECE");
        reportEntity.setSource(ucProblemTypeEntity.getTypeCode());
        reportEntity.setRamark(et_remark.getText().toString().trim());
        reportEntity.setDeviceId(SysInfo.getInstance().getImei());
        reportEntity.setDeviceDataId(Constants.getUUID());
        reportEntity.setDeleteFlag(false);
        showPgDlg("上报中...");
        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setUrl(Constants.URL_PROBLEM_UC_REPORT)
                .setRequestObject(reportEntity)
                .setResponsClazz(UcProblemReportResponse.class)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        showToast(msg);
                        SoundVibratorManager.playSound(2);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        UcProblemReportResponse response = (UcProblemReportResponse) obj;
                        if (response != null && response.getData() != null) {
                            if (response.getData().isSuccess()) {
                                showToast("上报问题件成功！");
                                SoundVibratorManager.playSound(1);
                                finish();
                            } else {
                                showToast("上报失败Tip:" + response.getData().getMessage());
                                SoundVibratorManager.playSound(2);
                            }
                        } else {
                            showToast("上报问题件失败！");
                            SoundVibratorManager.playSound(2);
                        }
                    }
                });
    }

    /**
     * 图片上传
     *
     * @param picType 照片类型：1-正常照片上传，2-修复前照片，3-修复后照片，
     */
    private void uploadImage(final int picType) {
        List<String> pickPic;
        if (picType == 1) {
            //正常照片
            pickPic = mGalleryPickView.getPickPicTakePhoto();
            if (pickPic.isEmpty()) {
                uploadImage(2);
                return;
            }
        } else if (picType == 2) {
            //修复前照片
            pickPic = mGalleryPickView.getPickPicBefor();
            if (pickPic.isEmpty()) {
                uploadImage(3);
                return;
            }
        } else {
            //修复后照片
            pickPic = mGalleryPickView.getPickPicAfter();
        }
        if (pickPic != null && !pickPic.isEmpty()) {
            showPgDlg("正在保存问题件图片数据...");
            Map param = new HashMap();
            //4为图片上传格式规范ID，8为视频上传规范ID
            param.put("uploaderStrategyId", "4");

            NetRequest request = new NetRequest();
            for (int i = 0; i < pickPic.size(); i++) {
                String item = pickPic.get(i);
                String fileName = item.substring(item.lastIndexOf("/") + 1);
                request.addFile("file" + i, fileName, new File(item));
            }
            request.setParams(param)
                    .setMethod(NetRequest.Method.POST)
                    .setUrl(Constants.URL_UPLOAD_IMAGE)
                    .setResponsClazz(ImageInfoResponse.class)
                    .execute(new UICallBack() {
                        @Override
                        public void onError(String msg) {
                            setScannerEnabled(true);
                            dismissPgDlg();
                            SoundVibratorManager.playSound(2);
                            if (msg != null) {
                                showToast("问题件图片数据保存失败:" + msg);
                            } else {
                                showToast("问题件图片数据保存失败!");
                            }
                        }

                        @Override
                        public void onSuccess(Object obj) {
                            ImageInfoResponse response = (ImageInfoResponse) obj;
                            String image = "";
                            for (ImageInfo item : response.getData()) {
                                image += item.getFileKey() + ",";
                            }
                            image = image.substring(0, image.length() - 1);
                            if (picType == 1) {
                                //正常上传照片
                                mImageIds = image;
                                uploadImage(2);
                            } else if (picType == 2) {
                                mImageBeforeIds = image;
                                uploadImage(3);
                            } else {
                                mImageAfterIds = image;
                                upload();
                            }
                        }
                    });
        } else {
            upload();
        }
    }

    /**
     * 校验问题件是否需要提供照片
     */
    private boolean checkProblemBillUpPic() {
        if (list2 != null) {
            int isAutoSubmitPicture = list2.get(uploadType2Spinner.getSelectedItemPosition()).getIsAutoSubmitPicture();
            if (isAutoSubmitPicture == 1) {
                return true;
            }
        }
        return false;
    }

    private void upload() {
        Abnormal mAbnormal = new Abnormal();
        mAbnormal.setWaybillNo(etWaybill.getText().toString().trim());
        mAbnormal.setAbnormalType(list.get(uploadTypeSpinner.getSelectedItemPosition()).getTypeCode());
        mAbnormal.setAbnormalCategory(list2.get(uploadType2Spinner.getSelectedItemPosition()).getTypeCode());
        mAbnormal.setAbnormalDetail(et_remark.getText().toString().trim());
        mAbnormal.setReportEmpCode(SharedPreferUtil.getInstance().getValue(Common.USER_CODE));
        String excpNum = exceptionNum.getText().toString().trim();
        if (!excpNum.equals("")) {
            mAbnormal.setErrorNum(Integer.parseInt(excpNum));
        }
        //设置车牌号
        mAbnormal.setCarNo(carNo.getText().toString().trim());
        //配载单号
        mAbnormal.setStowageNo(etCarCode.getText().toString().trim());
        //2-APP_Android,3-APP_IOS,4-PDA
        mAbnormal.setSource("4");
        //责任部门
        if (llZeRenDept.getVisibility() == View.VISIBLE) {
            mAbnormal.setNoticeDepartName(zeRenDept);
            mAbnormal.setNoticeDepartCode(zeRenDeptCode);
        }
        //是否修复
        if (spIsRepair.getVisibility() == View.VISIBLE) {
            if (spIsRepair.getSelectedItemPosition() == 0) {
                //是
                mAbnormal.setColumn2("1");
            } else {
                //否
                mAbnormal.setColumn2("0");
            }
        }
        //是否转差错,默认否
        mAbnormal.setMistakeType(0);
        if (llIsChaCuo.getVisibility() == View.VISIBLE) {
            if (chaCuoSpinner.getSelectedItemPosition() == 0) {
                //是
                mAbnormal.setMistakeType(1);
            }
        }
        //派送日期
        if (llDispatchTime.getVisibility() == View.VISIBLE) {
            mAbnormal.setDispatchTimeStr(tvDispatchTime.getText().toString().trim());
        }
        //设置正常上传图片id
        mAbnormal.setFileIds(mImageIds);
        //修复前照片
        mAbnormal.setPreprofileid(mImageBeforeIds);
        //修复后照片
        mAbnormal.setAfterfileid(mImageAfterIds);

        //关闭扫描
        setScannerEnabled(false);
        showPgDlg("正在保存问题件数据...");

        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setUrl(Constants.URL_UPLOAD_EXCEPTION)
                .setRequestObject(mAbnormal)
                .setResponsClazz(Object.class)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        //开启扫描
                        setScannerEnabled(true);
                        dismissPgDlg();
                        SoundVibratorManager.playSound(2);
                        if (msg != null) {
                            showToast("问题件数据保存失败:" + msg);
                        } else {
                            showToast("问题件数据保存失败!");
                        }
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        //开启扫描
                        setScannerEnabled(true);
                        dismissPgDlg();
                        SoundVibratorManager.playSound(1);
                        showToast("上报问题件成功！");
                        finish();
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case ZE_REN_DEPT_CODE:
                    //责任部门
                    zeRenDeptCode = data.getStringExtra("deptCode");
                    zeRenDept = data.getStringExtra("deptName");
                    tvZenRenDept.setText(zeRenDept);
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        switch (parent.getId()) {
            case R.id.spinner_uploadType:
                //问题类型
                if (!UcWaybillValidate.validate(etWaybill.getText().toString().trim())) {
                    //处理非快递单号，即快运单号
                    splist2.clear();
                    QueryQcTypeTable mQueryQcTypeTable = list.get(position);
                    if ("W002".equals(mQueryQcTypeTable.getTypeCode())) {
                        //破损，则显示是否修复选项
                        spIsRepair.setVisibility(View.VISIBLE);
                        if (spIsRepair.getSelectedItemPosition() == 0) {
                            //选择是，拍照上传照片隐藏，显示修复前、修复后
                            mGalleryPickView.showRepairPhotoLayout();
                            llIsChaCuo.setVisibility(View.VISIBLE);
                        } else {
                            //选择否，拍照上传照片显示，隐藏修复前、修复后
                            mGalleryPickView.showTakePhotoLayout();
                        }
                    } else {
                        spIsRepair.setVisibility(View.GONE);
                        llIsChaCuo.setVisibility(View.GONE);
                        mGalleryPickView.showTakePhotoLayout();
                    }
                    list2 = mQueryQcTypeTableDao.findChildLevel(mQueryQcTypeTable.getTypeCode(), 2);
                    if (list2 != null && list2.size() > 0) {
                        for (QueryQcTypeTable item : list2) {
                            splist2.add(item.getTypeName());
                        }
                    }
                    // 建立Adapter并且绑定数据源
                    adapterType2 = new SpinnerAdapter<>(this, R.layout.simple_spinner_item, splist2);
                    uploadType2Spinner.setAdapter(adapterType2);
                    showZeRenDept();
                }
                break;
            case R.id.spinner_uploadType2:
                //问题类别
                showZeRenDept();
                break;
            case R.id.spinner_isRepair:
                //是否修复
                if (spIsRepair.getSelectedItemPosition() == 0) {
                    String waybillNo = etWaybill.getText().toString().trim();
                    if ("".equals(waybillNo)) {
                        showToast("请扫描或填写运单号！");
                        spIsRepair.setSelection(1);
                        SoundVibratorManager.playSound(2);
                        return;
                    }
                    //选择是，拍照上传照片隐藏，显示修复前、修复后
                    mGalleryPickView.showRepairPhotoLayout();
                    //调用接口判断是否显示转差错
                    queryQcChaCuo();
                } else {
                    //选择否，拍照上传照片显示
                    mGalleryPickView.showTakePhotoLayout();
                    llIsChaCuo.setVisibility(View.GONE);
                }
                break;
            case R.id.spinner_isChaCuo:
                //转差错
                //调用质控接口, 校验这个是否已经转过差错，如果已经转过差错提示用户，否则默认设置为否
                if (chaCuoSpinner.getSelectedItemPosition() == 0) {
                    String waybillNo = etWaybill.getText().toString().trim();
                    if ("".equals(waybillNo)) {
                        showToast("请扫描或填写运单号！");
                        chaCuoSpinner.setSelection(1);
                        SoundVibratorManager.playSound(2);
                        return;
                    }
                    queryNeddMistake();
                }
                break;
            default:
                break;
        }
    }

    /**
     * 显示责任部门逻辑
     */
    private void showZeRenDept() {
        QueryQcTypeTable childQc = list2.get(uploadType2Spinner.getSelectedItemPosition());
        Integer isNeedToReply = childQc.getIsNeedToReply();
        if (isNeedToReply != null && isNeedToReply == 1) {
            //需要回复
            tvNeedReply.setVisibility(View.VISIBLE);
        } else {
            tvNeedReply.setVisibility(View.GONE);
        }
//                当需要回复（isNeedToReply=1）并且回复部门类型（replyDepartType）包含责任部门（4）时，需要显示责任部门并且必填
//                当需要知悉（isNeedToKnow=1）并且知悉部门类型（knowDepartType）包含责任部门（4）时，需要显示责任部门并且必填
        //当需要配载单（isStowageNo =1）并且知悉部门类型（knowDepartType）包含责任部门（4）需要显示责任部门并且必填
        //或回复部门类型（replyDepartType）包含责任部门（4）时，需要显示责任部门并且必填
        Integer isNeedToKnow = childQc.getIsNeedToKnow();
        String replyDepartType = childQc.getReplyDepartType();
        String knowDepartType = childQc.getKnowDepartType();
        Integer isStowageNo = childQc.getIsStowageNo();
        if (isNeedToReply != null && isNeedToReply == 1 && replyDepartType != null && replyDepartType.contains("4")) {
            llZeRenDept.setVisibility(View.VISIBLE);
        } else if (isNeedToKnow != null && isNeedToKnow == 1 && knowDepartType != null && knowDepartType.contains("4")) {
            llZeRenDept.setVisibility(View.VISIBLE);
        } else if ((isStowageNo != null && isStowageNo == 1 && knowDepartType != null && knowDepartType.contains("4"))
                || (replyDepartType != null && replyDepartType.contains("4"))) {
            llZeRenDept.setVisibility(View.VISIBLE);
        } else {
            llZeRenDept.setVisibility(View.GONE);
        }

        // 0 - PDA校验运单号必填即可。
        // 1 - PDA需校验配载单必填，运单号不可填。
        if (childQc.getIsStowageNo() == 0) {
            mIsStowageNo = 0;
            etWaybill.setHint("必填");
            tvWaybillTag.setVisibility(View.VISIBLE);
            etCarCode.setHint("非必填");
            tvStowageNoTag.setVisibility(View.INVISIBLE);
            etWaybill.setEnabled(true);
        } else {
            mIsStowageNo = 1;
            etCarCode.setHint("必填");
            tvStowageNoTag.setVisibility(View.VISIBLE);
            etWaybill.setHint("");
            etWaybill.setText("");
            tvWaybillTag.setVisibility(View.INVISIBLE);
            etWaybill.setEnabled(false);
        }

        //变更派送时间
        if ("W139".equals(childQc.getTypeCode())) {
            llDispatchTime.setVisibility(View.VISIBLE);
        } else {
            llDispatchTime.setVisibility(View.GONE);
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case GalleryPickView.REQUEST_CODE_PERMISSIONS:
                PermissionUtils.onRequestMorePermissionsResult(ProblemBillUploadActivity.this, GalleryPickView.PERMISSIONS, new PermissionUtils.PermissionCheckCallBack() {
                    @Override
                    public void onHasPermission() {
                        mGalleryPickView.takePhotoFunction(ProblemBillUploadActivity.this);
                    }

                    @Override
                    public void onUserHasAlreadyTurnedDown(String... permission) {
                        PermissionUtils.requestMorePermissions(ProblemBillUploadActivity.this, GalleryPickView.PERMISSIONS, GalleryPickView.REQUEST_CODE_PERMISSIONS);
                    }

                    @Override
                    public void onUserHasAlreadyTurnedDownAndDontAsk(String... permission) {
                        Common.showPermissionDialog(ProblemBillUploadActivity.this, "程序需要读取手机信息权限和文件读写权限，才能继续使用，请去权限界面打开！", GalleryPickView.REQUEST_CODE_PERMISSIONS);
                    }
                });
                break;
            default:
                break;
        }
    }

    /**
     * 查询是否需要转差错
     */
    private void queryQcChaCuo() {
        showPgDlg("查询中...");
        Map<String, String> params = new HashMap<>(1);
        params.put("waybillNo", etWaybill.getText().toString());
        new NetRequest().setMethod(NetRequest.Method.GET)
                .setResponsClazz(BooleanDataResponse.class)
                .setParams(params)
                .setUrl(Constants.URL_QUERY_WAYBILL_QC_AB)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        showToast(msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        BooleanDataResponse response = (BooleanDataResponse) obj;
                        if (response != null && response.getData()) {
                            //需要展示转差错
                            llIsChaCuo.setVisibility(View.VISIBLE);
                        } else {
                            //不需要隐藏转差错
                            llIsChaCuo.setVisibility(View.GONE);
                        }
                    }
                });
    }

    /**
     * 查询是否需要转差错
     */
    private void queryNeddMistake() {
        showPgDlg("查询中...");
        final String waybillNo = etWaybill.getText().toString();
        Map<String, String> params = new HashMap<>(1);
        params.put("waybillNo", waybillNo);
        new NetRequest().setMethod(NetRequest.Method.GET)
                .setResponsClazz(IntDataResponse.class)
                .setParams(params)
                .setUrl(Constants.URL_QUERY_MISTAKE_COUNT)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        showToast(msg);
                        chaCuoSpinner.setSelection(1);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        IntDataResponse response = (IntDataResponse) obj;
                        if (response != null && response.getData() > 0) {
                            //返回值大于0，说明已经转过差错，破损修复是否转差错自动选择否 并且提示
                            chaCuoSpinner.setSelection(1);
                            showToast("运单【" + waybillNo + "】已上报破损修复不可再次上报，破损修复是否转差错只能是否！");
                        }
                    }
                });
    }

    @Override
    public boolean showBack() {
        return false;
    }

    @Override
    public void setBack() {

    }

    @NotNull
    @Override
    public String setTitle() {
        return getPageName();
    }

}
